package com.lframework.jh.push.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.lframework.jh.push.core.components.resp.PageResult;
import com.lframework.jh.push.core.constants.StringPool;
import com.lframework.jh.push.core.exceptions.impl.DefaultClientException;
import com.lframework.jh.push.core.impl.BaseMpServiceImpl;
import com.lframework.jh.push.core.utils.Assert;
import com.lframework.jh.push.core.utils.IdUtil;
import com.lframework.jh.push.core.utils.ObjectUtil;
import com.lframework.jh.push.core.utils.PageHelperUtil;
import com.lframework.jh.push.core.utils.PageResultUtil;
import com.lframework.jh.push.core.utils.StringUtil;
import com.lframework.jh.push.service.annotations.OpLog;
import com.lframework.jh.push.service.entity.App;
import com.lframework.jh.push.service.enums.OpLogType;
import com.lframework.jh.push.service.mappers.AppMapper;
import com.lframework.jh.push.service.service.AppService;
import com.lframework.jh.push.service.vo.app.AppSelectorVo;
import com.lframework.jh.push.service.vo.app.CreateAppVo;
import com.lframework.jh.push.service.vo.app.QueryAppVo;
import com.lframework.jh.push.service.vo.app.UpdateAppVo;
import java.io.Serializable;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class AppServiceImpl extends BaseMpServiceImpl<AppMapper, App> implements AppService {

    @Override
    public PageResult<App> query(Integer pageIndex, Integer pageSize,
        QueryAppVo vo) {

        Assert.greaterThanZero(pageIndex);
        Assert.greaterThanZero(pageSize);

        PageHelperUtil.startPage(pageIndex, pageSize);
        List<App> datas = this.query(vo);

        return PageResultUtil.convert(new PageInfo<>(datas));
    }

    @Override
    public List<App> query(QueryAppVo vo) {

        return getBaseMapper().query(vo);
    }

    @Cacheable(value = App.CACHE_NAME, key = "#id", unless = "#result == null")
    @Override
    public App findById(String id) {

        return getBaseMapper().selectById(id);
    }

    @Override
    public PageResult<App> selector(Integer pageIndex, Integer pageSize,
        AppSelectorVo vo) {

        Assert.greaterThanZero(pageIndex);
        Assert.greaterThanZero(pageSize);

        PageHelperUtil.startPage(pageIndex, pageSize);
        List<App> datas = getBaseMapper().selector(vo);

        return PageResultUtil.convert(new PageInfo<>(datas));
    }

    @OpLog(type = OpLogType.APP, name = "新增应用，ID：{}, 名称：{}", params = {"#_result",
        "#vo.name"}, autoSaveParams = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String create(CreateAppVo vo) {

        Wrapper<App> checkWrapper = Wrappers.lambdaQuery(App.class)
            .eq(App::getName, vo.getName());
        if (getBaseMapper().selectCount(checkWrapper) > 0) {
            throw new DefaultClientException("名称重复，请重新输入！");
        }

        App data = new App();
        data.setId(IdUtil.getUUID());
        data.setName(vo.getName());
        data.setMchId(vo.getMchId());
        data.setAvailable(Boolean.TRUE);
        data.setDescription(
            StringUtil.isBlank(vo.getDescription()) ? StringPool.EMPTY_STR : vo.getDescription());

        getBaseMapper().insert(data);

        return data.getId();
    }

    @OpLog(type = OpLogType.APP, name = "修改应用，ID：{}, 名称：{}", params = {"#vo.id",
        "#vo.name"}, autoSaveParams = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(UpdateAppVo vo) {

        App data = this.findById(vo.getId());
        if (ObjectUtil.isNull(data)) {
            throw new DefaultClientException("应用不存在！");
        }

        Wrapper<App> checkWrapper = Wrappers.lambdaQuery(App.class)
            .eq(App::getName, vo.getName())
            .ne(App::getId, vo.getId());
        if (getBaseMapper().selectCount(checkWrapper) > 0) {
            throw new DefaultClientException("名称重复，请重新输入！");
        }

        LambdaUpdateWrapper<App> updateWrapper = Wrappers.lambdaUpdate(App.class)
            .set(App::getName, vo.getName())
            .set(App::getAvailable, vo.getAvailable())
            .set(App::getDescription,
                StringUtil.isBlank(vo.getDescription()) ? StringPool.EMPTY_STR
                    : vo.getDescription())
            .eq(App::getId, vo.getId());

        getBaseMapper().update(updateWrapper);
    }

    @CacheEvict(value = App.CACHE_NAME, key = "#key")
    @Override
    public void cleanCacheByKey(Serializable key) {

    }
}
